<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends MY_Controller {

	/**
	 * 假索引
	 * @var ConsumerMallModel
	 */
	public $mMall;
	
	public function __construct(){
		parent::__construct();
        $this->loadModel('ConsumerMallModel', 'mMall', 'consumer');
	}
	
	/**
	 * 首页
	 */
	public function index(){
		
		$data = array(
				'title'=>'礼品管理',
		);
		
		$this->view('mall/home/home', $data, 'datatable,select2,datepicker');
	}
	
	/**
	 * 详情
	 */
	public function details(){

		$info = $this->mMall->getInfo(get('id'));
		if ( ! $info){
			show_404();
		}
// 		print_r($info);
		$data = array(
				'title'=>'礼品管理',
				'info'=>$info,
		);
		
		$this->view('mall/home/details', $data, '');
	}

	/**
	 * 增加
	 */
	public function add(){
		$data = array(
				'title'=>'添加礼品',
				'add'=>1,
		);
		
		$this->view('mall/home/form', $data, 'ueditor,validation,fileinput,select2,webuploader,cropit_master');
	}
	
	/**
	 * 增加
	 */
	public function edit(){
		$info = $this->mMall->getInfo(get('id'));
		
		if ( ! $info){
			show_404();
		}

		$data = array(
				'title'=>'编辑礼品',
				'add'=>0,
				'info'=>$info,
		);
		
		$this->view('mall/home/form', $data, 'ueditor,validation,fileinput,select2,webuploader,cropit_master');
	}
	
	/**
	 * 获取列表
	 */
	public function getList(){
		$data = $this->mMall->adminGetList();
		foreach ($data['data'] as $k=>$v){
			$data['aaData'][$k][] = '<img src="'.getImage($v['imgurl'],'xs').'" class="img-wh" />';
			$data['aaData'][$k][] = $v['title'];
			$data['aaData'][$k][] = $v['integral'];
			$data['aaData'][$k][] = $v['hot'];
			$data['aaData'][$k][] = date('Y-m-d H:i:s',$v['addtime']);
            $status = $v['status'] == 1?2:1;
			$data['aaData'][$k][] = "<a href='".getUrl('mall/home/changeStatus?id='.$v['id'].'&status='.$status).
                "' class='ajax-request-btn deco' alert-message='确定要".$this->adminStatus($status).$v['title']."'>".$this->adminStatus($v['status'],true)."</a>";

			$btnConfig = adminCreateBtn(array(
							'label' => '详情',
							'attr' => array(
									'href' => getUrl('mall/home/details?id='.$v['id']),
									'class' => 'btn btn-xs green-stripe default'
							),
							'tag' => 'a'
					));

            $btnConfig .= ' '.adminCreateBtn(array(
							'label' => '编辑',
							'icon' => '',
							'attr' => array(
									'href' => getUrl('mall/home/edit?id='.$v['id']),
									'class' => 'btn btn-xs blue-stripe default edit-btn'
							),
							'tag' => 'a',
							'permissions' => array(
									'module' => 'classes',
									'key' => 'edit'
							)
					));
			$btnConfig .= ' '.adminCreateBtn(array(
							'label' => '删除',
							'icon' => '',
							'attr' => array(
									'href' => getUrl('mall/home/deleteMall?id='.$v['id']),
									'class' => 'btn btn-xs red-stripe default ajax-request-btn',
                                    'alert-message' => '是否确认删除 “ '.$v['title']." ” ？"
							),
							'tag' => 'a',
							'permissions' => array(
									'module' => 'classes',
									'key' => 'edit'
							)
					));
			$data['aaData'][$k][] = $btnConfig;
		}
		
		unset($data['data']);
		echo json_encode($data);
	}
	
	/**
	 * 修改|新增
	 */
	public function save(){
		//表单验证
		$vConf = array(
				array('title', '标题', 'required'),
				array('integral', '积分', 'required|is_natural_no_zero'),
				array('notice', '产品介绍', 'required'),
				array('introduce', '产品描述', 'required'),
		);
		$this->formDataValidation($vConf);
		
		$id = post('id');
		$title = post('title');
		$integral = post('integral');
		$notice = post('notice');
		$introduce = post('introduce');
		$images = post('showurl'); //轮播图
		$imgurl = post('imgurl'); //封面图

		if (! $id && !$imgurl){
			$this->ajaxReturn(0,'封面图未上传');
		}
		
		if (! $id && ! $images){
			$this->ajaxReturn(0,'轮播图未上传');
		}
		
		$data = array(
				'title'=>$title,
				'integral'=>$integral,
				'notice'=>$notice,
				'introduce'=>$introduce,
		);
		
		$this->db->trans_begin();
        $tA = array();
		if ($id){
            $tA = $this->mMall->getInfo($id);
            if(!$tA){
                $this->ajaxReturn(0, '礼品不存在');
            }
			$tId = $this->mMall->save($data,$id);
			if(!$tId){
				$this->db->trans_rollback();
				$this->ajaxReturn(0,'保存失败');
			}
		}else {
			$data['hot'] = 0;
			$data['status'] = 1;
			$data['addtime'] = time();
			$tId = $this->mMall->save($data);
			if(!$tId){
				$this->ajaxReturn(0,'保存失败');
			}
		}
		
		$tId = $id?:$tId;

		/**
		 *  移动新文件
		 */
		$imgPath = array();
		$path = 'uploads/mall/'.$tId.'/';
		if ($images){
			foreach ($images as $k=>$v){
				if (stripos($v,'temp') !== FALSE){
                    $size = getimagesize($v);
					$imgPath[] = saveTempImg($v,$path,true, $size[0], $size[1]);
				}else {
					$imgPath[] = str_replace(base_url(), '', $v);
				}
			}
		}

        $showurl = $tA['showurl'];
        if($id && $showurl){

            foreach ($showurl as $k=>$v){
                if( ! in_array($v, $imgPath)){
                    $v = strstr($v, '?',true);
                    $tA = explode('/', $v);
                    $filename = $tA[count($tA)-1];
                    if (file_exists($v)){
                        @unlink($v);
                    }
                    if (file_exists($path.'sm/'.$filename)){
                        @unlink($path.'sm/'.$filename);
                    }
                    if (file_exists($path.'xs/'.$filename)){
                        @unlink($path.'xs/'.$filename);
                    }
                }
            }
        }
        if($imgPath){
            $data['showurl'] = json_encode($imgPath);
        }
        if ($imgurl){
            $path = 'uploads/mall/'.$tId;
            $tA = saveCSVimg(array($imgurl), $path, 'imgurl');

            if( ! $tA){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '封面图上传失败');
            }
            $data['imgurl'] = $tA[0];

        }

		//保存
		$query = $this->mMall->save($data, $tId);
		if( ! $query){
			$this->db->trans_rollback();
			$this->ajaxReturn(0, '保存失败');
		}
		
		

		
		$this->db->trans_commit();
		$this->ajaxReturn(1,'保存成功','',getUrl('mall/home/index'));
		
	}

    /**
     * 删除
     */
    public function deleteMall(){
         //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mMall->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在或已删除');
        }

        $tA = $this->mMall->deleteMall($id);
        if (!$tA){
            $this->ajaxReturn(0, '删除失败');
        }
        $this->ajaxReturn(1, '删除成功');
    }

	/**
	 * 更改状态
	 */
	public function changeStatus(){
		$id = get('id');
		$status = get('status');
		if (! $id || ! $status || ! in_array($status, array(1,2))){
			$this->ajaxReturn(0,'参数错误');
		}
        $info = $this->mMall->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在');
        }
		if( ! $this->mMall->save(array('status'=>$status),$id)){
			$this->ajaxReturn(0,'保存失败');
		}
		$this->ajaxReturn(1,'保存成功');
	}
}
